package com.learner.course.service.impl;

import com.alibaba.fastjson.JSON;
import com.learner.common.exception.ExceptionUtil;
import com.learner.common.exception.RestException;
import com.learner.course.mapper.CourseMapper;
import com.learner.course.mapper.CoursePlanMapper;
import com.learner.course.repository.CourseBaseRepository;
import com.learner.course.repository.CourseDetailRepository;
import com.learner.course.repository.CourseMarketRepository;
import com.learner.course.repository.CoursePubRepository;
import com.learner.course.repository.TeacherRepository;
import com.learner.course.service.CourseBaseService;
import com.learner.course.service.CourseService;
import com.learner.pojo.course.CourseBase;
import com.learner.pojo.course.CourseDetail;
import com.learner.pojo.course.CourseMarket;
import com.learner.pojo.course.CoursePub;
import com.learner.pojo.course.Teacher;
import com.learner.pojo.course.expand.CoursePlanNode;
import com.learner.pojo.course.expand.CourseQueryVo;
import com.learner.pojo.course.expand.CourseView;
import com.learner.pojo.page.PageResult;
import com.learner.pojo.trade.dto.CourseDto;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @Description: 课程的综合处理
 * @Author: ice2020x
 * @Date: 2021/8/22
 */
@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private CoursePlanMapper coursePlanMapper;

    @Autowired
    private CourseMarketRepository courseMarketRepository;

    @Autowired
    private CourseBaseRepository courseBaseRepository;

    @Autowired
    private CourseBaseService courseBaseService;

    @Autowired
    private CoursePubRepository coursePubRepository;

    @Autowired
    private TeacherRepository teacherRepository;

    @Autowired
    private CourseDetailRepository courseDetailRepository;

    @Override
    public CourseView courseView(String id) {
        CourseView courseView = new CourseView();

        Optional<CourseBase> courseBaseOptional = courseBaseRepository.findById(id);

        CourseBase courseBase = null;
        if (courseBaseOptional.isPresent()) {
            courseBase = courseBaseOptional.get();
            courseView.setCourseBase(courseBase);
        }

        //课程营销信息
        Optional<CourseMarket> marketOptional = courseMarketRepository.findById(id);
        if (marketOptional.isPresent()) {
            CourseMarket courseMarket = marketOptional.get();
            courseView.setCourseMarket(courseMarket);
        }

        //课程计划信息
        CoursePlanNode coursePlan = coursePlanMapper.selectListByCourseId(id);
        courseView.setCoursePlanNode(coursePlan);

        Optional<CourseDetail> courseDetailOptional = courseDetailRepository.findById(id);
        if (courseDetailOptional.isPresent()) {
            CourseDetail courseDetail = courseDetailOptional.get();
            courseView.setCourseDetail(courseDetail);
        }

        if (courseBase != null) {
            String userid = courseBase.getUserId();
            Optional<Teacher> teacherOptional = teacherRepository.findById(userid);

            if (teacherOptional.isPresent()) {
                System.out.println(teacherOptional.get());
                Teacher teacher = teacherOptional.get();
                courseView.setTeacher(teacher);
            }
        }

        return courseView;
    }

    /**
     * 创建es的信息
     *
     * @param id 课程id
     */
    private CoursePub createCoursePub(String id) {
        CoursePub coursePub = new CoursePub();
        //根据课程id查询course_base
        Optional<CourseBase> baseOptional = courseBaseRepository.findById(id);
        CourseBase courseBase = null;
        if (baseOptional.isPresent()) {
            courseBase = baseOptional.get();
            System.out.println(courseBase);
            //将courseBase属性拷贝到CoursePub中
            BeanUtils.copyProperties(courseBase, coursePub);
            Optional<Teacher> teacherOptional = teacherRepository.findById(courseBase.getUserId());
            teacherOptional.ifPresent(teacher -> coursePub.setTeacherName(teacher.getName()));
        }


        //课程营销信息
        Optional<CourseMarket> marketOptional = courseMarketRepository.findById(id);
        if (marketOptional.isPresent()) {
            CourseMarket courseMarket = marketOptional.get();
            System.out.println(courseMarket);
            BeanUtils.copyProperties(courseMarket, coursePub);
        }

        //课程计划信息
        CoursePlanNode coursePlanNode = coursePlanMapper.selectListByCourseId(id);
        String jsonString = JSON.toJSONString(coursePlanNode);
        //将课程计划信息json串保存到 course_pub中
        coursePub.setCoursePlan(jsonString);


        return coursePub;

    }


    /**
     * @Description: 更新课程状态
     * @Author: ice2020x
     * @Date: 2021/10/13
     */
    private CourseBase saveCoursePubState(String courseId) {
        CourseBase courseBase = courseBaseService.getCourseBaseById(courseId);
        if (courseBase == null) {
            throw ExceptionUtil.createException(RestException.class, 2000006);
        }
        courseBase.setStatus("202002");
        courseBaseRepository.save(courseBase);
        return courseBase;
    }

    @Override
    public void publicCourse(String id) {
        CourseBase saveCoursePubState = this.saveCoursePubState(id);
        CoursePub coursePub = createCoursePub(id);
        saveCoursePub(id, coursePub);
    }


    /**
     * @Description: 保存CoursePub信息
     * @Author: ice2020x
     * @Date: 2021/10/13
     */
    private void saveCoursePub(String id, CoursePub coursePub) {
        CoursePub coursePubNew = null;
        Optional<CoursePub> optional = coursePubRepository.findById(id);
        // 如果不存在创建一个
        coursePubNew = optional.orElseGet(CoursePub::new);
        BeanUtils.copyProperties(coursePub, coursePubNew);
        coursePubNew.setId(id);
        coursePubNew.setTimestamp(new Date());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = simpleDateFormat.format(new Date());
        coursePubNew.setPubTime(date);
        coursePubRepository.save(coursePubNew);
    }


    @Override
    public PageResult<CourseView> findAllByCondition(CourseQueryVo courseQueryVo) {
        Sort sort = Sort.by(Sort.Direction.ASC, "id");
        Pageable pageable = PageRequest.of(courseQueryVo.getPage() - 1, courseQueryVo.getSize(), sort);
        Specification<CourseBase> specification = (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<Predicate>();
            if (null != courseQueryVo.getName() && !"".equals(courseQueryVo.getName())) {
                list.add(criteriaBuilder.like(root.get("name"), "%" + courseQueryVo.getName() + "%"));
            }
            if (null != courseQueryVo.getMt() && !"".equals(courseQueryVo.getMt())) {
                list.add(criteriaBuilder.equal(root.get("mt"), courseQueryVo.getMt()));
            }
            if (null != courseQueryVo.getSt() && !"".equals(courseQueryVo.getSt())) {
                list.add(criteriaBuilder.equal(root.get("st"), courseQueryVo.getSt()));
            }
            if (null != courseQueryVo.getUserid() && !"".equals(courseQueryVo.getUserid())) {
                list.add(criteriaBuilder.equal(root.get("userid"), courseQueryVo.getUserid()));
            }
            if (null != courseQueryVo.getStatus() && !"".equals(courseQueryVo.getStatus())) {
                list.add(criteriaBuilder.equal(root.get("status"), courseQueryVo.getStatus()));
            }
            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };
        org.springframework.data.domain.Page<CourseBase> repositoryAll = courseBaseRepository.findAll(specification, pageable);
        List<CourseBase> content = repositoryAll.getContent();
        List<CourseView> courseViews = new ArrayList<>();
        for (CourseBase courseBase : content) {
            courseViews.add(courseView(courseBase.getId()));
        }
        return new PageResult<>((long) courseViews.size(), courseViews);
    }

    /**
     * @Description: 根据id查询课程信息
     * @Author: ice2020x
     * @Date: 2021/10/26
     */
    @Override
    public CourseDto getCourseDtoById(String id) {
        return courseMapper.findCourseDtoById(id);
    }

    /**
     * @Description: 根据大分类获取课程信息
     * @Author: ice2020x
     * @Date: 2021/11/26
     */
    @Override
    public List<CourseBase> getCourseInfoByMt(String mt) {
        return null;
    }


}
